package com.tarena.baking.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置登录页面
        http.formLogin().loginPage("/login.html");
        //关闭跨域攻击防护
        http.csrf().disable();
        //配置黑名单列表
        String[] urls = {
                "/**/update",
                "/**/delete",
                "/**/insert",
                "/admin.html",
                "/personal.html",
                "/postContent.html",
                "/articleManagement.html"
        };
        //配置访问策略
        http.authorizeRequests() // 配置URL的访问控制
                .antMatchers(urls).authenticated() // urls里面的路径是需要登录的
                .anyRequest().permitAll(); // 剩下的所有请求是直接允许访问的

        // 配置未登录请求的异常处理
//        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
//            @Override
//            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
//                response.sendRedirect("/401.html");
//            }
//        });


    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


}
